package com.jimmy.gank.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.text.TextUtils;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import okhttp3.Cookie;

public class CookiesUtil {
    private static final String COOKIE_NAME = "cookie_name";
    private static final String COOKIE_VALUE = "cookie_value";
    private static final String COOKIE_HOST = "cookie_host";
    private static final String COOKIE_PATH = "cookie_path";
    private static final String COOKIE_EXPIRES = "cookie_expires";

    public static final String CURRENT_USER_ID = "current_user_id";
    public static final String CURRENT_PASSWORD = "current_password";


    private static final String CountryGardenCookie = "country_garden_cookie";

    public static void setCurrentUserAndPassWord(Context context, String currentUser, String passWord) {
        SharedPreferences sharedPreferences = getSystemPreferences(context);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(CURRENT_USER_ID, currentUser);
        editor.putString(CURRENT_PASSWORD, passWord);
        editor.apply();
    }

    public static String getCurrentUser(Context context) {
        SharedPreferences sharedPreferences = getSystemPreferences(context);
        return sharedPreferences.getString(CURRENT_USER_ID, "");
    }




    public static SharedPreferences getSystemPreferences(Context context) {
        return context.getSharedPreferences(CountryGardenCookie, Context.MODE_PRIVATE);
    }

    public static SharedPreferences getUserPreferences(Context context, String userName) {
        return context.getSharedPreferences(CountryGardenCookie + userName, Context.MODE_PRIVATE);
    }

    public static void saveLoginCookies(Context context, String currentUser, List<Cookie> cookies) {
        SharedPreferences sharedPreferences = getUserPreferences(context, currentUser);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        Set<String> cookieNames = new HashSet<>();
        for (Cookie cookie : cookies) {
            cookieNames.add(cookie.name());
            editor.putString(cookie.name() + COOKIE_VALUE, cookie.value());
            editor.putString(cookie.name() + COOKIE_HOST, cookie.domain());
            editor.putString(cookie.name() + COOKIE_PATH, cookie.path());
            editor.putLong(cookie.name() + COOKIE_EXPIRES, cookie.expiresAt());

        }
        editor.putStringSet(COOKIE_NAME, cookieNames);
        editor.apply();
    }

    public static void clearCookies(Context context,String currentUser){
        SharedPreferences sharedPreferences = getUserPreferences(context, currentUser);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
    }

    public static List<Cookie> getCookies(Context context, String currentUser) {
        List<Cookie> cookies = new ArrayList<>();
        SharedPreferences sharedPreferences = getUserPreferences(context, currentUser);
        Set<String> cookieNames = new HashSet<>();
        cookieNames = sharedPreferences.getStringSet(COOKIE_NAME, cookieNames);
        for (String cookieName : cookieNames) {
            String cookieValue = sharedPreferences.getString(cookieName + COOKIE_VALUE, "");
            String domain = sharedPreferences.getString(cookieName + COOKIE_HOST, "");
            String cookiePath = sharedPreferences.getString(cookieName + COOKIE_PATH,"");
            long  cookieExpire = sharedPreferences.getLong(cookieName + COOKIE_EXPIRES,0L);

            if (TextUtils.isEmpty(cookieValue) || TextUtils.isEmpty(domain))
                continue;
          Cookie.Builder builder= new Cookie.Builder()
                    .name(cookieName)
                    .value(cookieValue)
                    .expiresAt(cookieExpire)
                    .domain(domain).httpOnly()
                    .secure();

            if (cookiePath.startsWith("/")){
                builder.path(cookiePath);
            }
            Cookie cookie =  builder.build();
            cookies.add(cookie);
        }
        return cookies;
    }


    /**
     * 同步一下cookie
     */
    public static void synCookies(Context context, String url) {
        CookieManager cookieManager = CookieManager.getInstance();

        cookieManager.setAcceptCookie(true);
        String currentUser = getCurrentUser(context);
        List<Cookie> cookies = getCookies(context,currentUser);
        for (Cookie cookie : cookies){
            //cookieManager.setCookie(url, "UID=EBFDA984906B62C444931EA0");
            cookieManager.setCookie(cookie.domain(),cookie.name() + "=" + cookie.value());
        }
        if (Build.VERSION.SDK_INT < 21) {
            CookieSyncManager.getInstance().sync();
        } else {
            CookieManager.getInstance().flush();
        }
    }
}
